package com.haiheng.module_main.fragment.bookcar

import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView.OnEditorActionListener
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.constant.AppConstant.Companion.SP_USER_LOGIN
import com.haiheng.common.constant.Keys
import com.haiheng.common.constant.RourePage
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.SPUtils
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.bookcar.BookCarInfoAdapter
import com.haiheng.module_main.databinding.BookCarNoBookHintDialogBinding
import com.haiheng.module_main.databinding.FragmentBookCarInfoBinding
import com.haiheng.module_main.dialog.BookCarClearHintDialog
import com.haiheng.module_main.dialog.BookCarNoBookHintDialog
import com.haiheng.module_main.dialog.ScanDialog
import com.haiheng.module_main.mode.BookCarInfoViewModel
import com.haiheng.module_main.mode.BookCarShelfViewModel
import okhttp3.internal.checkOffsetAndCount


/**
 *
 * @Des: 书车信息页面
 * @Author: hwz
 * @Date:2024/8/16 0016
 * @Version: 1.0
 */

class BookCarInfoFragment : RouterFragment(), ScanDialog.OnScanResultCallback {
    private lateinit var binding: FragmentBookCarInfoBinding

    private val viewModel: BookCarInfoViewModel by viewModels()
    private val bookCarShelfViewModel: BookCarShelfViewModel by viewModels()

    private val bookCarInfoAdapter = BookCarInfoAdapter()
    private lateinit var scanDialog: ScanDialog
    private lateinit var loadingDialog : LoadingDialog

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBookCarInfoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun initView() {
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        var pageType = arguments?.get(Keys.PAGE_TYPE)
        var userlOgin = SPUtils.getInstance().getString(SP_USER_LOGIN)
        binding.includeBottom.slBottomRight.visibility = View.GONE
        if (RourePage.BOOK_CAR_SHELF.name.equals(pageType)){
           binding.includeTile.tvTitle.setText("图书上架")
        }else if (RourePage.BOOK_CAR_SCAN.name.equals(pageType)){
           binding.includeTile.tvTitle.setText("图书扫描")
           binding.includeBottom.tvBottomRight.setText("开始扫书")
        }
        binding.includeTile.tvCarName.visibility = View.GONE

        binding?.rvList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvList?.adapter = bookCarInfoAdapter

        binding.includeBottom.slBottomLeft.setOnClickListener {
//            var intent = Intent(activity,ScanActivity::class.java)
//            startActivity(intent)
            showScanDialog()
        }
        binding.includeBottom.slBottomRight.setOnClickListener {
            if (RourePage.BOOK_CAR_SCAN.name.equals(pageType)){
                activity.navigation(RourePage.BOOK_CAR_SCAN)
            }else if (RourePage.BOOK_CAR_SHELF.name.equals(pageType)){
                if (bookCarShelfViewModel.bookInfoList.value.isNullOrEmpty()){
                    BookCarNoBookHintDialog.newInstance().show(childFragmentManager)
                }else{
                    activity.navigation(RourePage.BOOK_CAR_SHELF)
                }
            }
        }

        binding.includeTile.sflBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.ivClearBacode.setOnClickListener {
            bookCarInfoAdapter.clearData()
            bookCarInfoAdapter.notifyDataSetChanged()
            binding.etBarCode.setText("")
            binding.includeBottom.slBottomRight.visibility = View.GONE
            binding.includeTile.tvClear.visibility = View.GONE
        }
        binding.etBarCode.setInputType(InputType.TYPE_CLASS_TEXT);
        binding.etBarCode.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.etBarCode.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                showLoadDiaog()
                viewModel.queryBookCarDetail(binding.etBarCode.text.toString())
                // 处理搜索逻辑
                true
            } else false
        })
        binding.includeTile.tvClear.setOnClickListener {
            BookCarClearHintDialog.newInstance()
                .setOnDialogListener(object :BookCarClearHintDialog.OnDialogClickListener{
                override fun onClear(dialog: BookCarClearHintDialog) {
                    bookCarShelfViewModel.clearBookData()
                    loadingDialog.setMessage("正在删除")
                    loadingDialog.show()
                    dialog.dismiss()

                }
            }).show(childFragmentManager)
        }
    }

    fun showLoadDiaog(){
        loadingDialog.setMessage("正在查询书车信息")
        loadingDialog.show()
    }

    fun showScanDialog() {
        // 在需要显示Dialog的时候才进行初始化
        if (!::scanDialog.isInitialized) {
            scanDialog = ScanDialog(requireActivity(), this) // 使用requireActivity()更安全
        }
        scanDialog.show()
    }

    override fun initViewModel(): BaseViewModel? {
        viewModel.bookCarInfoList.observe(viewLifecycleOwner) {
            loadingDialog.hide()
            bookCarInfoAdapter.setNewData(it)
            binding.includeTile.tvClear.visibility = View.VISIBLE
            binding.includeBottom.slBottomRight.visibility = View.VISIBLE

        }
        viewModel.failMsg.observe(viewLifecycleOwner){
            loadingDialog.hide()
            ToastUtils.showShort(it)
        }
        viewModel.isGetBookNum.observe(viewLifecycleOwner){
            bookCarShelfViewModel.getBookList()
        }
        bookCarShelfViewModel.bookInfoList.observe(viewLifecycleOwner){
            LogUtils.d("清除书车${it.size}")
            loadingDialog.hide()
            viewModel.updateBookCount(it.size)
        }
        bookCarShelfViewModel.faiMsg.observe(viewLifecycleOwner){
            loadingDialog.hide()
            LogUtils.d("清除书车${it}")
            if ("上架成功".equals(it)){
                bookCarShelfViewModel.clearAllBookListData()
            }
            binding.includeTile.tvClear.visibility = View.GONE
        }

        return viewModel
    }

    override fun initLoad() {

    }

    override fun onScanSuccess(result: String?) {
        binding.etBarCode.setText(result)
        showLoadDiaog()
        viewModel.queryBookCarDetail(result.toString())
    }

    override fun onScanError(error: String?) {

    }
}